package com.wandian.centerserver;

import com.wandian.executor.TimerCommand;
import com.wandian.texas.BaseCommandObject;
import com.wandian.texas.GameData;
import com.wandian.texas.ThreadPool;
import com.wandian.texas.UserMgr;
import com.wandian.texas.command.texas.CenterTimersCmd;
import com.wandian.texas.db.CommonDaoManager;
import com.wandian.texas.db.DBMgr;
import com.wandian.texas.db.Result;
import com.wandian.texas.entity.CornucopiaEntity;
import com.wandian.texas.SessionObject;
import com.wandian.util.ArrayList;
import com.wandian.util.Log;
import com.wandian.util.RandomUtil;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author long
 * @date 2012-12-9 下午3:29:42
 * @qq 108232706
 * @description CenterMgr
 */
public class CenterMgr {

	private static Map<String, TimerCommand> timers = new HashMap<String, TimerCommand>();
	private static Map<String, CornucopiaEntity> cornucopias = new HashMap<String, CornucopiaEntity>();
	private static final boolean synByMemory = true;
	private static float lastSynCornucopia = 0;
	private static float lastSynOffSetCornucopia = 0;
	private static float lastSynSystemTotalWin = 0;
	public static float offsetPerSecond = 24;
	public static int updateCornucopiaSecond = 30;
	public static TimeUnit updateCornucopiaTimeUnit = TimeUnit.SECONDS;
	/**
	 * 为了统计定时器任务次数 0,30秒推送积宝数 1,同步积宝数到db 2,同步积宝记录db
	 */
	public static int TimerTrickCounts[] = new int[3];
	static {
		CenterMgr.offsetPerSecond = GameData.getFloat("OffsetPerSecond");
		CenterMgr.updateCornucopiaSecond = Math.round(GameData.getFloat("UpdateCornucopiaSecond"));
		CenterMgr.updateCornucopiaTimeUnit = getTimeUnit(GameData.getString("UpdateCornucopiaSecond"));
	}

	public static TimerCommand getTimerCommand(String cornucopiaCallBack) {
		return timers.get(cornucopiaCallBack);
	}

	public static void timersDetail() {
		Log.info("[30秒推送积宝数]:" + TimerTrickCounts[0] + " [同步积宝数到db]:" + TimerTrickCounts[1] + "[同步积宝记录db]:" + TimerTrickCounts[2]);
		Iterator<TimerCommand> it = timers.values().iterator();
		while (it.hasNext()) {
			Log.info(it.next());
		}
		ThreadPool.getInstance().timersDetial();
	}

	public static TimeUnit getTimeUnit(String strTime) {
		if ("SECONDS".equals(strTime)) {
			return TimeUnit.SECONDS;
		}
		if ("MINUTES".equals(strTime)) {
			return TimeUnit.MINUTES;
		}
		if ("HOURS".equals(strTime)) {
			return TimeUnit.HOURS;
		}
		if ("DAYS".equals(strTime)) {
			return TimeUnit.DAYS;
		}
		if ("MILLISECONDS".equals(strTime)) {
			return TimeUnit.MILLISECONDS;
		}
		if ("MICROSECONDS".equals(strTime)) {
			return TimeUnit.MICROSECONDS;
		}
		if ("NANOSECONDS".equals(strTime)) {
			return TimeUnit.NANOSECONDS;
		}
		throw new IllegalArgumentException("getTimeUnit error");
	}

	public static void ALLOWCORNUCOPIA(BaseCommandObject cmdObject) {
		int roomId = cmdObject.readInt();
		int seatId = cmdObject.readInt();
		int userId = cmdObject.readInt();
		int idx = cmdObject.readInt();
		byte cardType = cmdObject.readByte();
		CornucopiaEntity cornucopia = new CornucopiaEntity();
		cornucopia.ServerId = (Integer) cmdObject.sessionObject.getAttribute("serverid");
		cornucopia.RoomId = roomId;
		cornucopia.SeatId = seatId;
		cornucopia.UserId = userId;
		cornucopia.idx = idx;
		cornucopia.CardType = cardType;
		cornucopia.CornucopiaCallBack = String.valueOf(System.nanoTime());
		cornucopia.CreatTime = new Timestamp(System.currentTimeMillis());
		cornucopia.CornucopiaType = 0;
		// 判断能不能出这个积宝，
		cmdObject.writeBegin();
		cmdObject.setCmd(CenterSessionMgr.CMD_ALLOWCORNUCOPIA);
		// 50%的几率
		if (RandomUtil.next(100) < 50) {// 如果成功
			cornucopia.IsAllow = true;
			cmdObject.writeByte((byte) 0);
			cmdObject.writeInt(roomId);
			cmdObject.writeInt(seatId);
			cmdObject.writeInt(userId);
			cmdObject.writeInt(idx);
			cmdObject.writeByte(cardType);
			cmdObject.writeString(cornucopia.CornucopiaCallBack);
			// 加入计时器任务，如10分钟取消该积宝
			TimerCommand timer = new TimerCommand("RECYCLE_ALLOWCORNUCOPIA", CenterSessionMgr.CMD_CENTER_SERVER_TIMERS, 10, TimeUnit.MINUTES);
			timer.put("Type", CenterTimersCmd.RECYCLE_ALLOWCORNUCOPIA);
			timer.put("Cornucopia", cornucopia);
			timer.put("SessionObject", cmdObject.sessionObject);
			timers.put(cornucopia.CornucopiaCallBack, timer);
			cornucopias.put(cornucopia.CornucopiaCallBack, cornucopia);
			ThreadPool.getInstance().Push(timer);
//			Log.error("加入计时器任务，如10分钟取消该积宝,成功");
		} else {
			cmdObject.writeByte((byte) 1);
			cmdObject.writeInt(roomId);
//			Log.error("拒绝了该积宝请求");
			cornucopiaRecords.add(cornucopia);
		}
		cmdObject.writeEnd();
		UserMgr.I().SendData(cmdObject);
		if (!CommonDaoManager.GameRoomDao(0).executeUpdate("sp_AddBonus_CenterServerLog", DBMgr.TexasPokerDB, cornucopia.CornucopiaCallBack, cornucopia.CornucopiaType, cornucopia.IsAllow, cornucopia.IsUsing, cornucopia.IsSend, cornucopia.ServerId, cornucopia.RoomId, cornucopia.GameId, cornucopia.SeatId, cornucopia.UserId, cornucopia.idx, cornucopia.NickName, cornucopia.WinMoney, cornucopia.CardType, cornucopia.MaxCards)) {
			throw new IllegalArgumentException("插入中心积宝失败");
		}
	}

	public static void USINGDCORNUCOPIA(BaseCommandObject cmdObject) {
		cmdObject.setCmd(CenterSessionMgr.CMD_USINGDCORNUCOPIA);
		int roomId = cmdObject.readInt();
		int seatId = cmdObject.readInt();
		int userId = cmdObject.readInt();
		byte cardType = cmdObject.readByte();
		String cornucopiaCallBack = cmdObject.readString();
		boolean isUsing = cmdObject.readByte() == 0 ? true : false;
		TimerCommand timer = timers.get(cornucopiaCallBack);
		// 不存在，应让游戏端取消，因为未曾产生过该记录
		if (timer == null) {

		} else {
			// 将10分钟定时器取消
			boolean boolSuc = ThreadPool.getInstance().cancel(timer);
			if (boolSuc) {
				Log.info("将10分钟RECYCLE_ALLOWCORNUCOPIA定时器取消成功,cornucopiaCallBack:" + cornucopiaCallBack);
			} else {
				Log.error("将10分钟RECYCLE_ALLOWCORNUCOPIA定时器取消失败,cornucopiaCallBack:" + cornucopiaCallBack);
			}
			timers.remove(cornucopiaCallBack);
			CornucopiaEntity cornucopia = cornucopias.get(cornucopiaCallBack);
			if (cornucopia == null || cornucopia.CardType != cardType) {
				throw new IllegalArgumentException("游戏端使用的积宝牌型与中心端存的不一致");
			}
			cornucopia.IsUsing = isUsing;
			// 如果游戏端不使用该积宝,回收
			if (!cornucopia.IsUsing) {
				cornucopiaRecords.add(cornucopia);
				cornucopias.remove(cornucopiaCallBack);
				if (!CommonDaoManager.GameRoomDao(0).executeUpdate("sp_AddBonus_GameServerLog", DBMgr.TexasPokerDB, cornucopia.CornucopiaCallBack, cornucopia.CornucopiaType, cornucopia.IsUsing, cornucopia.IsSend, cornucopia.ServerId, cornucopia.RoomId, cornucopia.GameId, cornucopia.SeatId, cornucopia.UserId, cornucopia.idx, cornucopia.NickName, cornucopia.WinMoney, cornucopia.CardType, cornucopia.MaxCards, "游戏端未使用")) {
					throw new IllegalArgumentException("插入游戏积宝失败");
				}
			}
		}
		// 更新该条callback的操作记录
	}

	/**
	 * 游戏端游戏结束通知，积宝牌已经摊牌了
	 * 
	 * @param cmdObject
	 */
	public static void SENDCORNUCOPIA(BaseCommandObject cmdObject) {
		int roomId = cmdObject.readInt();
		int gameId = cmdObject.readInt();
		int seatId = cmdObject.readInt();
		int userId = cmdObject.readInt();
		int idx = cmdObject.readInt();
		String nickName = cmdObject.readString();
		byte cardType = cmdObject.readByte();
		String cornucopiaCallBack = cmdObject.readString();
		boolean isShowCardAndWinCornu = cmdObject.readByte() == 0 ? true : false;
		CornucopiaEntity cornucopia = cornucopias.get(cornucopiaCallBack);
		// 不存在，应让游戏端取消，因为未曾产生过该记录
		if (cornucopia == null) {
			Log.error("游戏端游戏结束通知，积宝牌已经摊牌了,积宝不存在,回调id：" + cornucopiaCallBack);
			return;
		}
		if (cornucopia.CardType != cardType) {
			Log.error("游戏端游戏结束通知，积宝牌已经摊牌了,积宝牌型不一致,回调id：" + cornucopiaCallBack);
			cornucopia.IsSend = false;
			cornucopiaRecords.add(cornucopia);
			cornucopias.remove(cornucopiaCallBack);
			return;
		}
		cornucopia.RoomId = roomId;
		cornucopia.GameId = gameId;
		cornucopia.SeatId = seatId;
		cornucopia.UserId = userId;
		cornucopia.idx = idx;
		cornucopia.NickName = nickName;
		cornucopia.MaxCards = cmdObject.readString();
		// 积宝被摊牌使用
		if (isShowCardAndWinCornu) {
			float WinCornucopiaRate = 0;
			boolean isCornucopia = false;
			switch (cardType) {
			case 9:
				WinCornucopiaRate = GameData.CornucopiaRates[0];
				break;
			case 8:
				isCornucopia = true;
				WinCornucopiaRate = GameData.CornucopiaRates[1];
				break;
			case 7:
				isCornucopia = true;
				WinCornucopiaRate = GameData.CornucopiaRates[2];
				break;
			default:
				break;
			}
			if (isCornucopia) {
				// CornucopiaEntity cornucopia = new CornucopiaEntity(this, u);
				// float curCornucopia; =
				// DaoManager.GameRoomDao(cmdObject.dbIndex).getFloat("Cornucopia");
				// 验证完消息，算出积宝赢的钱，广播一则消息出去
				cornucopia.WinMoney = Math.round(WinCornucopiaRate * GameData.getCornucopia());
				GameData.InCreaceCornucopia(-cornucopia.WinMoney);
				// 广播一则消息出去
				cmdObject.setCmd(CenterSessionMgr.CMD_BROADCASTSENDCORNUCOPIA);
//				cmdObject.setCmd(CenterSessionMgr.CMD_SENDCORNUCOPIA);
				cmdObject.writeBegin();
				cmdObject.writeInt(Integer.valueOf(cmdObject.sessionObject.getAttribute("serverid").toString()));
				cmdObject.writeInt(roomId);
				cmdObject.writeInt(userId);
				cmdObject.writeInt(idx);
				cmdObject.writeString(nickName);
				cmdObject.writeString(cornucopiaCallBack);
				cmdObject.writeByte(cardType);
				cmdObject.writeFloat(cornucopia.WinMoney);
				cmdObject.writeEnd();
				UserMgr.I().broadCastToAllOnlines(cmdObject);
				cornucopia.IsSend = true;
				cornucopiaRecords.add(cornucopia);
				cornucopias.remove(cornucopiaCallBack);
			}
		} else {
			// 玩家不摊牌，积宝取消
			cornucopia.IsSend = false;
			cornucopiaRecords.add(cornucopia);
			cornucopia.WinMoney = 0;
			cornucopias.remove(cornucopiaCallBack);
		}

		if (!CommonDaoManager.GameRoomDao(0).executeUpdate("sp_AddBonus_GameServerLog", DBMgr.TexasPokerDB, cornucopia.CornucopiaCallBack, cornucopia.CornucopiaType, cornucopia.IsUsing, cornucopia.IsSend, cornucopia.ServerId, cornucopia.RoomId, cornucopia.GameId, cornucopia.SeatId, cornucopia.UserId, cornucopia.idx, cornucopia.NickName, cornucopia.WinMoney, cornucopia.CardType, cornucopia.MaxCards, "游戏端请求")) {
			throw new IllegalArgumentException("插入游戏积宝失败");
		}

	}

	/**
	 * 中心服所有定时器操作的启动
	 */
	public static void startAllTimer() {
		if (!ThreadPool.getInstance().isThreadPoolStated()) {
			Log.error("=======线程池没有启动,定时器不能启动====");
			return;
		}
		startUpdateCornucopiaPer30s();
		startSynCornucopiaToDb();
//		startInsertCornucopiaRecord();
	}

	/**
	 * 如5分钟去保存一次最新的积宝日志，然后清空
	 */
	private static void startInsertCornucopiaRecord() {
		TimerCommand timer = timers.get("insertCornucopiaRecord");
		if (timer != null)
			timer.setCancel(false);
		else {
			timer = new TimerCommand("insertCornucopiaRecord", CenterSessionMgr.CMD_CENTER_SERVER_TIMERS, 1, 1, -1, TimeUnit.MINUTES);
			timer.put("Type", CenterTimersCmd.INSERTCORNUCOPIARECORD);
			timers.put("insertCornucopiaRecord", timer);
		}
		ThreadPool.getInstance().Push(timer);

	}

	public static void insertCornucopiaRecord() {
		TimerTrickCounts[2]++;
		if (cornucopiaRecords.size() < 1) {
//			Log.info("\\\\同步最新的积宝日志,数据暂时没有");
			return;
		}

//		Log.info("开始同步最新的积宝日志.....");
		Result rs = new Result() {
			@Override
			public void run() {
				try {
					ArrayList<CornucopiaEntity> cornucopiaRecordList = (ArrayList<CornucopiaEntity>) this.dataList;
					CornucopiaEntity tempCornucopia;
					for (int i = 0; i < cornucopiaRecordList.size(); i++) {
						tempCornucopia = cornucopiaRecordList.get(i);
						this.prepareAddBatch(tempCornucopia.CornucopiaCallBack, tempCornucopia.CornucopiaType, tempCornucopia.IsAllow, tempCornucopia.IsUsing, tempCornucopia.IsSend, tempCornucopia.ServerId, tempCornucopia.RoomId, tempCornucopia.GameId, tempCornucopia.SeatId, tempCornucopia.UserId, tempCornucopia.idx, tempCornucopia.NickName, tempCornucopia.WinMoney, tempCornucopia.CardType, tempCornucopia.MaxCards);
					}

				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		};
		CommonDaoManager.GameRoomDao(0).execBatchProcedure(rs, DBMgr.TexasPokerDB, "sp_AddCornucopiasRecord", 15, cornucopiaRecords);
		if (rs.IsSuccess) {
			cornucopiaRecords.clear();
//			Log.info("同步积宝记录成功");
		} else {
//			Log.error("同步全局数据成功");
		}
		rs = null;
	}

	public static void stopAllTimer() {
		if (!ThreadPool.getInstance().isThreadPoolStated()) {
			Log.error("=======线程池没有启动,定时器不需要停止====");
			return;
		}
		TimerCommand timer = timers.get("UpdateCornucopiaPer30s");
		if (timer != null) {
			timer.setCancel(true);
			ThreadPool.getInstance().cancel(timer);
		}
		timer = timers.get("synCornucopiaToDb");
		if (timer != null) {
			timer.setCancel(true);
			ThreadPool.getInstance().cancel(timer);
		}
		timer = timers.get("insertCornucopiaRecord");
		if (timer != null) {
			timer.setCancel(true);
			ThreadPool.getInstance().cancel(timer);
		}
		TimeToUpdateCornucopia(null);
		synCornucopiaToDb();
		insertCornucopiaRecord();
	}

	/**
	 * 如，5分钟去同步全局数据,
	 */
	private static void startSynCornucopiaToDb() {
		TimerCommand timer = timers.get("synCornucopiaToDb");
		if (timer != null)
			timer.setCancel(false);
		else {
			timer = new TimerCommand("synCornucopiaToDb", CenterSessionMgr.CMD_CENTER_SERVER_TIMERS, 1, 1, -1, TimeUnit.MINUTES);
			timer.put("Type", CenterTimersCmd.SYNCORNUCOPIATODB);
			timers.put("synCornucopiaToDb", timer);
		}
		ThreadPool.getInstance().Push(timer);
	}

	public static void synCornucopiaToDb() {
//		Log.info("\\\\开始同步全局t_config数据.....");
		TimerTrickCounts[1]++;
		if (CenterMgr.lastSynCornucopia == GameData.getCornucopia() && CenterMgr.lastSynOffSetCornucopia == GameData.getOffSetCornucopia() && CenterMgr.lastSynSystemTotalWin == GameData.getSystemTotalWin()) {
//			sLog.info("全局数据没有变化,不写入db");
			return;
		}
		// [sp_SynCornucopiaToDb]
		// 同步数据,游戏抽成数据，当前积宝变化数据
		Result rs = new Result() {
			@Override
			public void run() {
				try {
					if (this.stmt.getInt(1) == 0) {
						this.IsSuccess = true;
					}

				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		};
		//可以使用线程的db
		CommonDaoManager.GameRoomDao(0).execFreeProcedure(rs, DBMgr.TexasPokerDB, "sp_SynCornucopiaToDb", 1, GameData.getCornucopia(), GameData.getOffSetCornucopia(), GameData.getSystemTotalWin());
		if (rs.IsSuccess) {
			CenterMgr.lastSynCornucopia = GameData.getCornucopia();
			CenterMgr.lastSynOffSetCornucopia = GameData.getOffSetCornucopia();
			CenterMgr.lastSynSystemTotalWin = GameData.getSystemTotalWin();
//			Log.info(String.format("同步t_config成功,盈利:%s，积宝:%s，积宝盈余:%s",CenterMgr.lastSynSystemTotalWin,CenterMgr.lastSynCornucopia,CenterMgr.lastSynOffSetCornucopia));
		} else {
			Log.error("同步t_config failure");
		}
		//暂时没用到
//		CommonDaoManager.GameRoomDao(0).execFreeProcedure(rs, DBMgr.WANDIAN, "sp_AddSynMoneyLog", 1, rs.IsSuccess, GameData.getCornucopia(), GameData.getOffSetCornucopia(), GameData.getSystemTotalWin());
	}

	/**
	 * 定时去推送积宝,30秒更新一次，积宝起点,增长量
	 */
	private static void startUpdateCornucopiaPer30s() {
		// 从数据库取数,如果能24*30，返回0，否则返回1，表明偏移量不够
		TimerCommand timer = timers.get("UpdateCornucopiaPer30s");
		if (timer != null)
			timer.setCancel(false);
		else {
			timer = new TimerCommand("UpdateCornucopiaPer30s", CenterSessionMgr.CMD_CENTER_SERVER_TIMERS, updateCornucopiaSecond, updateCornucopiaSecond, -1, updateCornucopiaTimeUnit);
			timer.put("Type", CenterTimersCmd.UPDATECORNUCOPIAPER30S);
			timers.put("UpdateCornucopiaPer30s", timer);
		}
		ThreadPool.getInstance().Push(timer);

	}

	public static void TimeToUpdateCornucopia(TimerCommand cmd) {
//		Log.info("\\\\定时去推送积宝,30秒更新一次,正在执行....");
		TimerTrickCounts[0]++;
		float totalOffsetCornucopia = offsetPerSecond * updateCornucopiaSecond;
		if (!synByMemory) {
			//此方法不是靠内存维护数据
			Result rs = new Result() {
				@Override
				public void run() {
					try {
						if (!this.IsSuccess || this.RowSize < 1)
							return;
						this.DataRows = new Object[1][2];
						if (this.ResultSet.next()) {
							this.DataRows[0][0] = this.ResultSet.getInt(1);
							this.DataRows[0][1] = this.ResultSet.getInt(2);
						}
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			};
			CommonDaoManager.GameRoomDao(0).execProcedure(rs, "sp_UpdateCornucopiaPerSeconds", totalOffsetCornucopia);
			float fromCornucopia = (Float) rs.DataRows[0][0];
			float offsetCornucopia = (Float) rs.DataRows[0][1];
			if (offsetCornucopia > 0) {
				GameData.setCornucopia(fromCornucopia);// db同步到内存
				broadcastUpdateCornucopiaPer30s(cmd, fromCornucopia, offsetCornucopia);
			}
		} else {
			if (UserMgr.I().onlineUserList.size() > 0 && GameData.getOffSetCornucopia() > totalOffsetCornucopia) {
				GameData.InCreaceOffSetCornucopia(-totalOffsetCornucopia);
				GameData.InCreaceCornucopia(totalOffsetCornucopia);
				broadcastUpdateCornucopiaPer30s(cmd, GameData.getCornucopia(), totalOffsetCornucopia);// float-->int
																										// ？error
			} else {
//				Log.info("由于游戏积宝偏移量一直很小,或游戏端连线0,无法增加到积宝中去，取消定时广播积宝");
			}
		}

	}

	/**
	 * 定时去推送积宝,30秒更新一次，积宝起点,增长量
	 */
	private static void broadcastUpdateCornucopiaPer30s(TimerCommand cmd, float toCornucopia, float offsetCornucopia) {
//		Log.info("\\\\当前积宝toCornucopia：" + toCornucopia + " offsetCornucopia:" + offsetCornucopia);
		// 广播消息给全部在线,
		BaseCommandObject command = ThreadPool.getInstance().takeFreeCommand(cmd);
//		DataPacket dataPacket = new DataPacket(CenterSessionMgr.CMD_BROADCASTUPDATECORNUCOPIAPER30S);
		command.setCmd(CenterSessionMgr.CMD_BROADCASTUPDATECORNUCOPIAPER30S);
		command.writeBegin();
		command.writeFloat(toCornucopia);// 数据库返回最终数,让客户端在指定时间滚动
		command.writeFloat(offsetCornucopia);
		command.writeInt(updateCornucopiaSecond);// 告诉客户端时间
		command.writeEnd();
		UserMgr.I().broadCastToAllOnlines(command);
	}

	/**
	 * 游戏端一连接,第一次必须发送积宝，不管有没有偏移量
	 * 
	 * @param session
	 */
	public static void sendUpdateCornucopiaPer30s(BaseCommandObject cmdObject) {
		Log.info("\\\\游戏端连接，发送积宝");
		float totalOffsetCornucopia = offsetPerSecond * updateCornucopiaSecond;
		if (GameData.getCornucopia() < totalOffsetCornucopia)
			totalOffsetCornucopia = 0;
		cmdObject.setCmd(CenterSessionMgr.CMD_BROADCASTUPDATECORNUCOPIAPER30S);
		cmdObject.writeBegin();
		cmdObject.writeFloat(GameData.getCornucopia());// 数据库返回最终数,让客户端在指定时间滚动
		cmdObject.writeFloat(totalOffsetCornucopia);
		cmdObject.writeInt(updateCornucopiaSecond);// 告诉客户端时间
		cmdObject.writeEnd();
		UserMgr.I().SendData(cmdObject);
	}

	private static void stopUpdateCornucopiaPer30s() {
		TimerCommand timer = timers.get("UpdateCornucopiaPer30s");
		if (timer != null)
			timer.setCancel(true);
	}

	// private static ArrayList<GameWinRecord> gameWinRecords = new
	// ArrayList<GameWinRecord>();
	/**
	 * 积宝日志，在一个积宝生命周期结束，加入列表，定时器会存，并清空
	 */
	private static ArrayList<CornucopiaEntity> cornucopiaRecords = new ArrayList<CornucopiaEntity>();

	/**
	 * 中心端验证盈利累,
	 * 
	 * @param cmdObject
	 */
	public static void SENDSYSTEMTOTALWIN(BaseCommandObject cmdObject) {
		int roomid = cmdObject.readInt();
		int gameId = cmdObject.readInt();
		float systemWin = cmdObject.readFloat();// 如果是游戏结束，则表示把一局的抽成
		float systemTotalWin = cmdObject.readFloat();// 游戏端未发送的累积盈利
		float ToCornucopia = systemTotalWin * GameData.ToCornucopiaRate;
		// 更新游戏记录表，二次抽至积宝，内存的积宝偏移量增加
		GameData.InCreaceOffSetCornucopia(ToCornucopia);
		GameData.InCreaceSystemTotalWin(systemTotalWin - ToCornucopia);
		// gameWinRecords.add(new GameWinRecord(gameId, systemWin,
		// systemTotalWin, ToCornucopia));
		// 与游戏端确认成功
		/*cmdObject.setCmd(CenterSessionMgr.CMD_SENDSYSTEMTOTALWIN);
		cmdObject.writeBegin();
		cmdObject.writeByte((byte) 0);
		cmdObject.writeEnd();
		UserMgr.I().SendData(cmdObject);*/
	}

	/**
	 * CMD_BROADCASTTIMEOUTCORNUCOPIA 固定时间,未收到游戏端确认，回收积宝指标
	 * 
	 * @param cmd
	 */
	public static void RECYCLE_ALLOWCORNUCOPIA(TimerCommand cmd) {
		CornucopiaEntity cornucopia = (CornucopiaEntity) cmd.get("Cornucopia");
		if (cornucopia == null) {
			String error = "固定时间,未收到游戏端确认，回收积宝指标，cornucopia null ";
			Log.error(error);
			throw new IllegalArgumentException(error);
		}
		SessionObject session = (SessionObject) cmd.get("SessionObject");
		BaseCommandObject command = ThreadPool.getInstance().takeFreeCommand(cmd);
		command.setCmd(CenterSessionMgr.CMD_BROADCASTTIMEOUTCORNUCOPIA);
//		DataPacket dataPacket = new DataPacket(CenterSessionMgr.CMD_BROADCASTTIMEOUTCORNUCOPIA);
		command.writeBegin();
		command.writeInt(cornucopia.RoomId);
		// dataPacket.writeInt(cornucopia.SeatId);
		// dataPacket.writeInt(cornucopia.UserId);
		// dataPacket.writeByte((byte) cornucopia.CardType);
		command.writeString(cornucopia.CornucopiaCallBack);
		command.writeEnd();
		UserMgr.I().SendData(session, command);
		cornucopia.IsUsing = false;
		// 如果游戏端不使用该积宝,回收
		cornucopiaRecords.add(cornucopia);
		cornucopias.remove(cornucopia.CornucopiaCallBack);
		if (!CommonDaoManager.GameRoomDao(0).executeUpdate("sp_AddBonus_GameServerLog", DBMgr.TexasPokerDB, cornucopia.CornucopiaCallBack, cornucopia.CornucopiaType, cornucopia.IsUsing, cornucopia.IsSend, cornucopia.ServerId, cornucopia.RoomId, cornucopia.GameId, cornucopia.SeatId, cornucopia.UserId, cornucopia.idx, cornucopia.NickName, cornucopia.WinMoney, cornucopia.CardType, cornucopia.MaxCards, "超时")) {
			throw new IllegalArgumentException("插入游戏积宝失败");
		}
		Log.info("固定时间,未收到游戏端确认，回收积宝指标成功");
	}

	class GameWinRecord {
		public int ServerId;
		public int RoomId;
		public int GameId;
		public int SystemWin;
		public int SystemTotalWin;
		public int ToCornucopia;

		public GameWinRecord(int gameId, int systemWin, int systemTotalWin, int toCornucopia) {
			this.GameId = gameId;
			this.SystemWin = systemWin;
			this.SystemTotalWin = systemTotalWin;
			this.ToCornucopia = toCornucopia;
		}
	}
}
